package com.smart.service.redis;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.smart.consts.AppContants;
import com.smart.consts.AppInteractiveState;
import com.smart.consts.RedisKeysContants;


//@Service("redisService")
public class RedisServiceImpl implements RedisService {
	//@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Override
	public void set(String key, String val) {
		redisTemplate.opsForValue().set(key, val);
	}

	@Override
	public void set(String key, String val, long timeout) {
		redisTemplate.opsForValue().set(key, val, timeout, TimeUnit.SECONDS);
	}

	@Override
	public String get(String key) {
		return redisTemplate.opsForValue().get(key);
	}
	@Override
	public <T> Map<Object, Object> getCacheMap(String key){
		Map<Object, Object> map = redisTemplate.opsForHash().entries(key);
		return map;
	}
	
	@Override
	public boolean checkToken(Map<String, Object> headerMap) {
		if(headerMap.get(AppContants.APP_TOKEN)==null||"".equals(headerMap.get(AppContants.APP_TOKEN).toString())){
			headerMap.put(AppContants.APP_RESPCODE, AppInteractiveState.TOKEN_ERROR);
			headerMap.put(AppContants.APP_RESPMSG, "未检测到参数token!");
			return false;
		}
		String cacheToken = getTokenByUuid((String) headerMap.get(AppContants.APP_TOKEN));
		String tokenParm = (String) headerMap.get(AppContants.APP_TOKEN);
		if(cacheToken.equals(tokenParm)) {
			return true;
		}
		return false;
	}
	/**
	 * 获取UUID(实质就是客户端传过来的token) 对应的token
	 * @author zhuyong
	 * 
	 */
	public String getTokenByUuid(String uuid){
		Map<Object, Object> tokenMap = getCacheMap(RedisKeysContants.TOKEN_KEY);
		if(tokenMap==null){
			return "";
		}
		String code = "";
		if(tokenMap.get(uuid)!=null){
			code = tokenMap.get(uuid).toString();
		}
		return code;
	}
}
